import Vue from 'vue';
import Vuex from 'vuex';
import config from '@/common/config/config.js';
import router from '@/common/utils/router.js';
import dialog from '@/common/utils/dialog.js';
import {
	getRouteUrl
} from '@/common/utils/router.js';

// 该引用在APP无效
// import theme from '@/common/style/cg.scss';

import app from '@/common/config/app.js';
Vue.use(Vuex);


import uniPackage from '@/common/utils/uni-package.js'


import auth from '@/common/utils/auth.js';



import {
	loginMpWx,
	loginMpWxMobile
} from '@/api/common.js'



// import {
// 	init
// } from '@/api/common.js'


// 需要永久存储，且下次APP启动需要取出的，在state中的变量名
let saveStateKeys = ['token', 'userType', '$userInfo', '$position'];

// 保存变量到本地存储中
const saveCGDATA = function(key, value) {
	// console.log(key, value)
	// 判断变量名是否在需要存储的数组中
	if (saveStateKeys.indexOf(key) != -1) {
		// 获取本地存储的CGDATA对象，将变量添加到对象中
		let tmp = uni.getStorageSync('CGDATA');
		// 第一次打开APP，不存在CGDATA变量，故放一个{}空对象
		tmp = tmp ? tmp : {};
		tmp[key] = value;
		// 执行这一步后，所有需要存储的变量，都挂载在本地的CGDATA对象中
		// console.log('tmp:', tmp)
		uni.setStorageSync('CGDATA', tmp);
	}
}
const store = new Vuex.Store({
	state: {
		tabbarParams:{
			
		},
		userType: '', //用户身份，家长member或老师teacher
		token: '',
		dict: {
			// 数据字典
		},
		$position: {
			longitude: '',
			latitude: ''
		},
		$userInfo: {
			token: '',
			wallet: {}
		}, //登录用户信息
		...app,
		...config,
		/* app web mp-weixin */
		plantform: uni.getSystemInfoSync().uniPlatform === 'app' ? 'app' : 'miniProgram',
		loginType: uni.getSystemInfoSync().uniPlatform === 'app' ? 'app' : 'wechat',
		dirtyFlags: {} // 结构：{ '列表页唯一标识': boolean }


	},
	getters: {
		isTeacher(state) {
			return state.userType === 'teacher'
		}
	},
	mutations: {
		$CGStore(state, payload) {
			// 判断是否多层级调用，state中为对象存在的情况，诸如user.info.score = 1
			let nameArr = payload.name.split('.');
			let saveKey = '';
			let len = nameArr.length;
			if (nameArr.length >= 2) {
				let obj = state[nameArr[0]];
				for (let i = 1; i < len - 1; i++) {
					obj = obj[nameArr[i]];
				}
				obj[nameArr[len - 1]] = payload.value;
				saveKey = nameArr[0];
			} else {
				// 单层级变量，在state就是一个普通变量的情况
				state[payload.name] = payload.value;
				saveKey = payload.name;
			}
			// 保存变量到本地，见顶部函数定义
			saveCGDATA(saveKey, state[saveKey])
		},

		SET_TOKEN(state, token) {
			store.commit('$CGStore', {
				name: 'token',
				value: token
			})
			state.token = token;
		},
		SET_CLIENT(state, client) {
			state.client = client;
		},
		SET_ACCOUNT(state, account) {
			state.account = account;
		},
		SETDICT(state, dict) {
			state.dict = {
				...state.dict,
				...dict
			};
		},
		SET_USERINFO(state, userInfo) {
			state.$userInfo = userInfo;
		},
		SET_RELOAD(state, reload) {
			state.reload = reload;
		},
		SET_VIDEOPLAY(state, play) {
			console.log(play)
			state.videoPlay = play;
		},
		SET_ACCOUNTINFO(state, accountInfo) {
			state.accountInfo = accountInfo;
		},
		SET_CLINIC(state, clinic) {
			state.clinic = clinic;
		},
		SET_PLANTCONFIG(state, config) {
			state.plantConfig = config
		},
		SET_CDNPATH(state, cdnPath) {
			state.cdnPath = cdnPath
		},
		SET_SHOP(state, shop) {
			state.$shop = shop
		},
		SET_ORDERTYPE(state, type) {
			state.orderType = type
		},
		SET_DIRTYFLAG(state, {
			pageKey,
			isDirty
		}) {
			state.dirtyFlags[pageKey] = isDirty;
		},
		RESET_DIRTYFLAG(state, pageKey) {
			state.dirtyFlags[pageKey] = false;
		},
		setTabbarParams(state, params) {
			state.tabbarParams[params.key] = params.params;
		}

	},
	actions: {
		async login({
			state,
			commit,
			dispatch
		}, user) {
			return new Promise(async (resolve, reject) => {
				/* loginType
				 *  pass账号密码登录 phone手机号登录 wechat微信登录
				 */
				dialog.loading()
				console.log('user', user);
				const data = {
					"userType": state.userType,
					...user
				}
				let token;
				if (state.userType === 'teacher') {
					let res = await teacherLogin(data);
					token = res.token

				} else {
					let res = await login(data);
					token = res.token
				}
				console.log(token)
				if (!token) {
					// 没有token,需要去绑定手机号
					router.replace('/pages/account/mobile-bind')
					reject()
				} else {
					commit('$CGStore', {
						name: 'token',
						value: token
					})
					await dispatch('updateUserInfo', {
						force: true
					})
					router.switchTab('/pages/index/index')
					resolve()
				}

				dialog.hideLoading()
				// this.$CGRouter.push('./mobile-bind')
			})
		},

		// 微信小程序一键授权登录 (获取用户基本信息)
		LoginMpWx({
			commit
		}, data) {
			return new Promise((resolve, reject) => {
				loginMpWx({
						form: data
					}, {
						isPrompt: false
					})
					.then(response => {
						const result = response.data
						commit('SET_TOKEN', result.token)
						// commit('SET_USER_ID', result.userId)

						resolve(response)
					})
					.catch(reject)
			})
		},

		// 微信小程序一键授权登录 (授权手机号)
		LoginMpWxMobile({
			commit
		}, data) {
			return new Promise((resolve, reject) => {
				loginMpWxMobile({
						form: data
					}, {
						isPrompt: false
					})
					.then(response => {
						const result = response.data
						commit('SET_TOKEN', result.token)
						// commit('SET_USER_ID', result.userId)
						resolve(response)
					})
					.catch(reject)
			})
		},
		async logout({
			commit
		}, e) {
			return new Promise(async (resolve, reject) => {
				commit('SET_USERINFO', {})
				commit('SET_TOKEN', '');
				auth.clearStorage()
				router.reLaunch('/pages/account/user-type-select')
				resolve()
			})
		},
		updateUserInfo({
			commit,
			state,
			dispatch
		}, config) {
			return new Promise(async (resolve, reject) => {
				config = config || {}
				const userinfo = state.$userInfo
				if (!config.force) {
					if (userinfo) {
						commit('$CGStore', {
							name: '$userInfo',
							value: userinfo
						})
					}

				}

				// console.log('7878', 1);
				try {
					if (!userinfo || config.force) {
						if (!state.token) {
							reject()
							return
						}
						console.log('7878', 2);
						let {
							data
						} = await userInfo();
						console.log('7878', 3);
						console.log(data);
						commit('$CGStore', {
							name: '$userInfo',
							value: data
						})
						if (Number(data.havePassword) === 0) {
							router.replace('/pages/account/mobile-bind')
							reject()
							return
						}

					}

					resolve()
				} catch (e) {
					console.log('7878', 4);
					console.log(e)

					reject()
				}






			})

		},
		getDict({
			state,
			commit
		}, type) {
			return new Promise(async (resolve, reject) => {
				if (state.dict[type]) {
					resolve(state.dict[type]);
				} else {
					const {
						data
					} = await dict(type);
					const dicts = {
						[type]: data
					}
					commit('SETDICT', dicts);
					resolve(data)
				}
			})
		},
		updateAccountInfo({
			commit
		}, accountInfo) {
			commit('SET_ACCOUNTINFO', accountInfo);
			auth.setStorage({
				key: 'accountInfo',
				value: accountInfo
			})
		},
		updateClinic({
			commit
		}, clinic) {
			commit('SET_CLINIC', clinic);

		},
		updatePlantConfig({
			commit
		}, config) {
			return new Promise((resolve, reject) => {

				init().then(res => {
					console.log(res)
					commit('SET_PLANTCONFIG', res.data);
					commit('SET_CDNPATH', res.data.uploaddata.cdnurl)
					resolve()
				}).catch(err => {
					console.error(err);
					reject(err)
				})
			})
		},
		async setTabBarRedDot() {
			const {
				data
			} = await isNoLook();
			if (data) {
				uni.setTabBarBadge({
					index: 1,
					text: String(data)
				})
			} else {
				uni.removeTabBarBadge({
					index: 1,

				})
			}
		},
		setDirtyFlag({
			commit
		}, config = {
			pageKey: getRouteUrl(),
			isDirty: true

		}) {

			commit('SET_DIRTYFLAG', config)
		},
		resetDirtyFlag({
			commit
		}, pageKey = getRouteUrl()) {
			commit('RESET_DIRTYFLAG', pageKey)
		}

	},
	modules: {

	},
})

// 从缓存中取得相同的key进行覆盖操作
let CGDATA = uni.getStorageSync('CGDATA') || {};
for (let key in CGDATA) {
	if (store.state.hasOwnProperty(key)) {
		store.commit('$CGStore', {
			name: key,
			value: CGDATA[key]
		})
	}
}

export default store;